package com.zking.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义的拦截器的类   类中有三个方法
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    //ctrl+o  重写接口中的方法

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("login preHandle-------------");
        System.out.println("session----"+request.getSession().getAttribute("username"));
        if(request.getSession().getAttribute("username")==null){
          System.out.println("您没有登录！！！");
          //重定向到指定的请求     前端页面
        // response.sendRedirect("/user/show");
              // 获取到项目名，以便下面进行重定向
              String homeUrl = request.getContextPath();
              // 如果是 ajax 请求，则设置 session 状态 、CONTEXTPATH 的路径值
              // 如果是ajax请求响应头会有，x-requested-with
              if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
                  response.setHeader("SESSIONSTATUS", "TIMEOUT");
                  response.setHeader("CONTEXTPATH", homeUrl + "/pages/login.html");
                  // FORBIDDEN，forbidden。也就是禁止、403
                  response.setStatus(HttpServletResponse.SC_FORBIDDEN);
              } else {
                  // 如果不是 ajax 请求，则直接跳转即可
                  response.sendRedirect(homeUrl + "/pages/login.html");
              }
              return false;
          } else {
                return true;//放行后面的两个方法
         }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("login postHandle------------");
        //HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("login afterCompletion-----------------");
    }
}
